﻿using AIClient.Configs;
using AIClient.Gates;
using AIClient.Players;
using AIClient.Utils;
using NetWorkMsg;
using NFX;
using SharpYaml.Serialization;
using System;
using System.Collections.Concurrent;
using System.IO;
using System.Threading;

namespace AIClient
{
    public class Manager
    {
        public static    Manager                            Instance;
        public readonly  ConcurrentDictionary<long, Player> Players;
        public readonly  ObjectPool<MemoryStream>           BufferPool;
        private          int                                _timeStamp;
        private readonly Timer                              _timer;

        public readonly MessageHub MessageHub;

        public int TimeStamp => _timeStamp;

        public Manager(string cfgPath)
        {
            Instance = this;
            ConfigManager.Initialize(cfgPath);
            Players    = new ConcurrentDictionary<long, Player>();
            MessageHub = new MessageHub();
            BufferPool = new ObjectPool<MemoryStream>(() => new MemoryStream(MessageConst.StreamBufferSize));
            _timeStamp = 0;
            _timer     = new Timer(TimerUpdateProc, null, 0, (long) TimeSpan.FromSeconds(1).TotalMilliseconds);
        }

        // 启动
        public ManualResetEvent Start()
        {
            Logger.MakeLogger();
            return MessageHub.Start();
        }

        // 关闭
        public void Stop()
        {
            _timer.Dispose();
            Players.Values.ForEach(player => player.Stop());
            BufferPool.Clear();
            Logger.Clear();

            Instance = null;
        }

        // 更新时间
        public void UpdateTimeStamp(int timeStamp)
        {
            Interlocked.Exchange(ref _timeStamp, timeStamp);
        }

        // 启动AI
        public void StartPlayer(long playerId)
        {
            Players.TryAdd(playerId, new Player(playerId));
        }


        // 本地进行时间戳更新
        private void TimerUpdateProc(object _)
        {
            if (_timeStamp == 0) return;

            Interlocked.Increment(ref _timeStamp);
        }
    }
}